#include <user/ulib.h>
#include <user/file_server.h>

void
up_manager_dispatch(void)
{
	 set_user_service(SVC_UP_MANAGER, self_idx);
	 uint16_t idx;
	 uint32_t num;
	 struct pipe_t *in_pipe, *out_pipe;

	 out_pipe = pipe_open(service_callback);
	 uint32_t zero = 0;
	 pipe_block_write(out_pipe, &zero, sizeof(uint32_t));
	 pipe_close(out_pipe);

	 struct file_t *root = file_open_root();

	 while (1) {
		  rpc_recv(&idx, &num, &in_pipe, &out_pipe);
		  kprintf("spawn request");
		  
		  uint32_t n;
		  pipe_block_read(in_pipe, &n, sizeof(uint32_t));

		  kprintf(", n = %d", n);
		  char *buf = (char *)malloc(n + 1);
		  kprintf(", ");
		  
		  pipe_block_read(in_pipe, buf, n);
		  buf[n] = '\0';

		  kprintf("name = %s\n", buf);

		  file_seek(root, FS_SEEK_FIND, 0);
		  file_write(root, buf, n);
		  struct file_t *file = file_open(root);

		  iec_send(initial_idx, file->node, 0, 0, 0);
		  waitb(ENV_SCH_IEC_SEND_BLOCKING);
		  
		  rpc_return(idx, in_pipe, out_pipe);
	 }
}

void
up_manager_entry(void)
{
	 up_manager_dispatch();
}
